package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 20:08
 * @注释
 */
public class DirectProducer {
    //定义交换机的名称
    private static final String EXCHANGE_NAME = "direct_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        try (Connection connection=factory.newConnection();
             Channel channel= connection.createChannel()){
            //创建一个交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()){
                //读取用户输入的一行内容，并以空格作为分割
                String userInput= scanner.nextLine();
                String[] strings = userInput.split(" ");
                if(strings.length<1){
                    continue;
                }
                //获取内容消息
                String message=strings[0];
                String routingKey = strings[1];
                //发布消息到交换机，并指定路由键
                channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "with routing:" + routingKey + "'");
            }

        }
    }
}
